package com.jus.player.adapter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.PagerAdapter;

import com.alibaba.fastjson2.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.gms.common.util.CollectionUtils;
import com.jus.player.R;
import com.jus.player.activity.BaseActivity;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.VideoEntity;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.StringUtils;
import com.jus.player.util.cache.PreloadManager;
import com.jus.player.widget.component.FullScreenPlayerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class JsPlayerAdaptor extends PagerAdapter {

    // 添加一个SparseArray来缓存视图
    private final SparseArray<View> mActiveViews = new SparseArray<>();
    /**
     * View缓存池，从ViewPager中移除的item将会存到这里面，用来复用
     */
    private final List<View> mViewPool = new ArrayList<>();
    /**
     * 数据源
     */
    private List<VideoEntity> mVideoList;
    private final BaseActivity mActivity;

    // 在Adapter类中添加回调接口实例成员变量
    private final JsPlayerAdaptor.OnItemBtnClickListener listener;

    // 在Adapter的构造器中传入回调接口实例
    public JsPlayerAdaptor(BaseActivity activity, JsPlayerAdaptor.OnItemBtnClickListener listener) {
        this.mActivity = activity;
        this.listener = listener;
    }


    @Override
    public int getCount() {
        return mVideoList == null ? 0 : mVideoList.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Context context = container.getContext();
        View view = mViewPool.isEmpty() ? LayoutInflater.from(context).inflate(R.layout.item_full_screen_player, container, false)
                : mViewPool.remove(0);
        ViewHolder viewHolder;
        if (view.getTag() == null) {
            viewHolder = new ViewHolder(view);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
            // 重置可能为null的视图
            if (viewHolder.mPlayerView == null) {
                viewHolder.mPlayerView = view.findViewById(R.id.full_screen_player_View);
            }
        }
        //绑定数据
        bindData(viewHolder, mVideoList.get(position), position);

        // 为item的展开剧集弹窗视图设置点击监听器
        viewHolder.selectEpisode.setOnClickListener(v -> {
            if (listener != null) {
                listener.onShowEpisodesClick(mVideoList);
            }
        });
        viewHolder.playBack.setOnClickListener(v -> this.mActivity.finish());

        container.addView(view);
        mActiveViews.put(position, view); // 添加视图到缓存
        return view;
    }

    private void bindData(ViewHolder viewHolder, VideoEntity item, int position) {
        Context context = viewHolder.itemView.getContext();
        viewHolder.mPosition = position;
        viewHolder.tvId = item.getId();
        viewHolder.episode = item.getEpisode();

        if (!StringUtils.isEmpty(item.getTvDownloadUrl())) {
            PreloadManager.getInstance(context).addPreloadTask(item.getTvDownloadUrl(), position);
        }
        if (!StringUtils.isEmpty(item.getTvCoverUrl())) {
            Glide.with(context)
                    .load(item.getTvCoverUrl())
                    .into(viewHolder.mThumb);
        }
        viewHolder.mTitle.setText(item.getTitle());
        viewHolder.episodeNum.setText(context.getString(R.string.str_no)
                + " " + item.getEpisode() + " " + context.getString(R.string.str_episode));

        if (Objects.equals(item.getTotalEpisode(), item.getUpdateEpisode())) {
            viewHolder.updateEpisode.setText(context.getString(R.string.str_total) + " "
                    + item.getTotalEpisode() + " " + context.getString(R.string.str_episode));
        } else {
            viewHolder.updateEpisode.setText(context.getString(R.string.str_update_to) + " "
                    + item.getUpdateEpisode() + context.getString(R.string.str_episode));
        }
        viewHolder.followText.setText(context.getString(R.string.like));
        viewHolder.recommendText.setText(context.getString(R.string.str_recommend));
        List<JSONObject> typeList = item.getTypeList();
        if (!CollectionUtils.isEmpty(typeList)) {
            for (JSONObject jo : typeList) {
                if (Objects.equals(jo.getInteger("lastEpisode"), item.getEpisode())
                        && jo.getInteger("type") == AppConfig.INT_0) {
                    viewHolder.followBtn.setSelected(true);
                    viewHolder.followText.setText(context.getString(R.string.already_like));
                }
                if (Objects.equals(jo.getInteger("lastEpisode"), item.getEpisode())
                && jo.getInteger("type") == AppConfig.INT_1) {
                    if (jo.getBoolean("currRecommend")) {
                        viewHolder.recommendBtn.setSelected(true);
                    }
                    viewHolder.recommendText.setText(String.valueOf(jo.getLong("recommend")));
                }
            }
        }
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        View itemView = (View) object;
        ViewHolder holder = (ViewHolder) itemView.getTag();
        holder.releasePlayer(); // 关键：释放播放器资源

        container.removeView(itemView);
        mActiveViews.remove(position);
        VideoEntity item = mVideoList.get(position);
        //取消预加载
        if (!StringUtils.isEmpty(item.getTvDownloadUrl())) {
            PreloadManager.getInstance(container.getContext()).removePreloadTask(item.getTvDownloadUrl());
        }
        //保存起来用来复用
        mViewPool.add(itemView);
    }
    // 新增方法：获取指定位置的视图
    public View getViewByPosition(int position) {
        return mActiveViews.get(position);
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        // 强制所有item重建，确保位置正确
        return POSITION_NONE;
    }

    /**
     * 自定义的消息处理 ViewHolder
     */
    public class ViewHolder extends RecyclerView.ViewHolder {

        public int mPosition;
        public TextView mTitle;//标题
        public ImageView mThumb;//封面图
        public ImageView playBack;
        public FullScreenPlayerView mPlayerView;
        public FrameLayout mPlayerContainer;
        public LinearLayout selectEpisode;//视频展开选集
        public ImageView followBtn;
        public TextView followText;
        public ImageView recommendBtn;
        public TextView recommendText;
        public TextView episodeNum;
        public TextView updateEpisode;
        public Long tvId;
        public Integer episode;

        ViewHolder(View itemView) {
            super(itemView);
            playBack = itemView.findViewById(R.id.play_back);
            mPlayerView = itemView.findViewById(R.id.full_screen_player_View);
            mTitle = mPlayerView.findViewById(R.id.tv_title);
            mThumb = mPlayerView.findViewById(R.id.iv_thumb);

            followBtn = mPlayerView.findViewById(R.id.follow_Btn);
            followText = mPlayerView.findViewById(R.id.follow_text);
            recommendBtn = mPlayerView.findViewById(R.id.recommend_Btn);
            recommendText = mPlayerView.findViewById(R.id.recommend_text);
            episodeNum = mPlayerView.findViewById(R.id.episodeNum);
            updateEpisode = mPlayerView.findViewById(R.id.updateEpisode);
            selectEpisode = mPlayerView.findViewById(R.id.selectEpisode);
            mPlayerContainer = itemView.findViewById(R.id.full_screen_player_container);
            itemView.setTag(this);
            followBtn.setOnClickListener(v -> {
                followBtn.setSelected(!followBtn.isSelected());
                if (followBtn.isSelected()) {
                    followText.setText(mActivity.getString(R.string.already_like));
                } else {
                    followText.setText(mActivity.getString(R.string.like));
                }
                //增加或者删除追剧数据
                Map<String, String> map = new HashMap<>();
                map.put("episode", episode + "");
                map.put("type", "0");
                map.put("tvId", tvId + "");
                map.put("state", followBtn.isSelected() + "");
                updateFollowState(map);
            });

            //推荐点击事件
            recommendBtn.setOnClickListener(v -> {
                recommendBtn.setSelected(!recommendBtn.isSelected());
                if (recommendBtn.isSelected()) {
                    recommendText.setText(recommendText.getText().equals(mActivity.getString(R.string.str_recommend)) ? "1" : String.valueOf(Integer.parseInt(String.valueOf(recommendText.getText())) + 1));
                } else {
                    recommendText.setText(Integer.parseInt(String.valueOf(recommendText.getText())) > 1 ? String.valueOf(Integer.parseInt(String.valueOf(recommendText.getText())) -1) : mActivity.getString(R.string.str_recommend));
                }
                //增加或者删除追剧数据
                Map<String, String> map = new HashMap<>();
                map.put("episode", episode + "");
                map.put("type", "1");
                map.put("tvId", tvId + "");
                map.put("state", recommendBtn.isSelected() + "");
                updateFollowState(map);
            });
        }


        public void releasePlayer() {
            if (mPlayerView != null) {
                mPlayerView.release(); // 确保内部调用 player.release()
                mPlayerView = null;
            }
        }

        /**
         * 网络请求：更新追剧状态
         *
         * @param map map
         */
        private void updateFollowState(Map<String, String> map) {
            OkHttpHelper.getInstance(mActivity).getAsync(ApiConfig.UPDATE_USER_TV, map,
                    new OkHttpHelper.HttpCallback() {
                        @Override
                        public void onSuccess(String res) {
                        }

                        @Override
                        public void onFailure(OkHttpHelper.HttpException e) {
                            CommonUtils.showToastAsync(mActivity, e.getMessage());
                        }
                    });
        }
    }

    public void setVideoList(List<VideoEntity> videoList) {
        this.mVideoList = new ArrayList<>(videoList); // 防御性拷贝
        mActiveViews.clear(); // 数据变化时清空缓存
        mViewPool.clear();
        // 确保在主线程通知更新
        if (Looper.myLooper() == Looper.getMainLooper()) {
            notifyDataSetChanged();
        } else {
            new Handler(Looper.getMainLooper()).post(this::notifyDataSetChanged);
        }
    }

    // 增加检查方法
    public boolean isPositionValid(int position) {
        return position >= 0 && position < getCount() && mVideoList.get(position) != null;
    }

    // 在Adapter类中定义点击事件回调接口
    public interface OnItemBtnClickListener {
        void onShowEpisodesClick(List<VideoEntity> videoList);
    }

}
